package com.example.ecas.utils;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;


/**
 * java调用python的执行器
 */
@Component
public class PythonExecutor {
    public static List<String> execPythonFile(String fileLocation, String args) throws IOException, InterruptedException {
        List<String> pretreatmentResult = new ArrayList<>();
        String[] pythonRunningArgs = new String[] { "python",   //python执行
                fileLocation,   //文件路径，包含文件名
                args};          //参数，目前只支持一个
        Process proc;
        proc=Runtime.getRuntime().exec(pythonRunningArgs);

        //用输入输出流来截取结果

        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), Charset.forName("gbk")));
        String line = null;
        while ((line = in.readLine()) != null) {
            pretreatmentResult.add(line);
        }
        in.close();
        proc.waitFor();
        return pretreatmentResult;
    }

    public static List<String> execPythonFile(String fileLocation, List<String> args) throws IOException, InterruptedException {
        List<String> pretreatmentResult = new ArrayList<>();
        String[] pythonRunningArgs = new String[2 + args.size()];
        pythonRunningArgs[0] = "python";
        pythonRunningArgs[1] = fileLocation;
        for (int i = 0; i < args.size(); i++) {
            pythonRunningArgs[i+2] = args.get(i);
        }
        Process proc;
        proc=Runtime.getRuntime().exec(pythonRunningArgs);

        //用输入输出流来截取结果

        BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream(), Charset.forName("gbk")));
        String line = null;
        while ((line = in.readLine()) != null) {
            pretreatmentResult.add(line);
        }
        in.close();
        proc.waitFor();
        return pretreatmentResult;
    }
}
